from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
from models import db, Material, Process, Product, ProductMaterial, ProductProcess
from excel_import import bp as excel_bp

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@127.0.0.1/product_pricing'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'dev'

db.init_app(app)
app.register_blueprint(excel_bp)

@app.route('/')
def index():
    products = Product.query.all()
    return render_template('index.html', products=products)

@app.route('/materials')
def materials():
    materials = Material.query.all()
    return render_template('materials.html', materials=materials)

@app.route('/processes')
def processes():
    processes = Process.query.all()
    return render_template('processes.html', processes=processes)

@app.route('/products')
def products():
    products = Product.query.all()
    return render_template('products.html', products=products)

@app.route('/product/<int:product_id>')
def product_detail(product_id):
    product = Product.query.get_or_404(product_id)
    return render_template('product_detail.html', product=product)

@app.route('/add_material', methods=['POST'])
def add_material():
    try:
        material = Material(
            name=request.form['name'],
            specification=request.form['specification'],
            brand=request.form['brand'],
            model=request.form['model'],
            unit=request.form['unit'],
            price=float(request.form['price'])
        )
        db.session.add(material)
        db.session.commit()
        flash('材料添加成功')
    except Exception as e:
        db.session.rollback()
        flash(f'添加失败：{str(e)}')
    return redirect(url_for('materials'))

@app.route('/add_product', methods=['POST'])
def add_product():
    try:
        product = Product(
            name=request.form['name'],
            category=request.form['category'],
            specification=request.form['specification']
        )
        db.session.add(product)
        db.session.commit()
        return jsonify({'success': True, 'message': '产品添加成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'添加失败：{str(e)}'})

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True)